//
//  GMap.m
//  Speedater
//
//  Created by NgoThang on 1/2/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GMap.h"
#import "MAnnotation.h"
#import "MKMapView+ZoomLevel.h"
#import "MapOverlay.h"
#import "MapOverlayView.h"
#import "Start.h"
#import "ContactDetail.h"
#import "AppDelegate.h"
#import "JSON.h"

#define ZOOM_LEVEL 14
#define degreesToRadians(x) (M_PI * (x) / 180.0)

@interface GMap (Private)

- (void)cleanup;

@end

@implementation GMap (Private)

- (void)cleanup
{
    if (responseData != nil) {
        responseData = nil;
    }
    
    self.myMKMapView = nil;
    self.radiusBarItem = nil;
    self.locationArray = nil;
    self.friendUsername = nil;
}

@end


@implementation GMap

@synthesize myMKMapView;
@synthesize radiusBarItem;
@synthesize locationArray;
@synthesize friendUsername;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        localRadius = 0;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"GMAP -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (void)checkButtonTapped:(id)sender
{
    UIButton *tempButton = sender;

    [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];

    ContactDetail *contactDetail = [[ContactDetail alloc] init];
    contactDetail.friendUsername = [NSString stringWithString:tempButton.titleLabel.text];
    [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] pushViewController:contactDetail animated:YES];
    [contactDetail release];
    
    self.tabBarController.selectedIndex = 2;
}

- (void)addOnGoogleMap
{    
    //NSLog(@"%@", locationArray);
    for (id annotation in myMKMapView.annotations) {
        if ([annotation isKindOfClass:[MAnnotation class]]){
            [myMKMapView removeAnnotation:annotation];
        }
    }
    
    CLLocationCoordinate2D l0 = CLLocationCoordinate2DMake(0.0, 0.0);
    
    for(NSDictionary *dict in locationArray){
        CLLocationCoordinate2D l;
        NSDictionary *location = [dict objectForKey:@"location"];
        
        l.latitude = [[location objectForKey:@"lat"] floatValue];
        l.longitude = [[location objectForKey:@"lon"] floatValue];
        
        NSString *username = [dict objectForKey:@"username"];
        NSString *myUsername = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
        
        if ([myUsername isEqualToString:username])
        {
            l0 = l;
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:YES] autorelease]];
            //NSLog(@"-> %@", username);
        }
        else 
        {   if (!friendUsername)
        {
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:NO] autorelease]];
            //NSLog(@"-> %@", username);
        }
        else if ([friendUsername isEqualToString:username])
        {
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:NO] autorelease]];
            //NSLog(@"-> %@", username);
        }
        }
    }
    
    int radius = localRadius ? localRadius : [[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue];
    int zoom_level = (radius == 4500) ? 11 : ZOOM_LEVEL;
    [myMKMapView setCenterCoordinate:l0 zoomLevel:zoom_level animated:NO];
    
    MapOverlay *mapOverlayTemp = [[MapOverlay alloc] init];
    mapOverlayTemp.coordinate = l0;
    [myMKMapView addOverlay:mapOverlayTemp];
    [mapOverlayTemp release];
    if (mapOverlay)
    {
        [myMKMapView removeOverlay:mapOverlay];
        mapOverlay = nil;
    }
    mapOverlay = mapOverlayTemp;
}

- (void)updateRadiusText:(NSInteger)radius
{
    [radiusBarItem setTitle:[NSString stringWithFormat:@"%d Metern", localRadius]];
}

- (void)loadLocations:(NSInteger)radius
{
    AppDelegate *d = [[UIApplication sharedApplication] delegate];
    
    //NSLog(@"GPS(%f, %f)", d.lat, d.lon);
    
    localRadius = radius?radius:(localRadius?localRadius:[[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue]);
    [self updateRadiusText:localRadius];
    
    NSString *postString = [NSString stringWithFormat:@"op=loadLocationList&username=%@&radius=%d&lat=%f&lon=%f",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            localRadius, d.lat, d.lon];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        //HUD.alpha = 0.02;
        [HUD show:YES];
    }
    [conn release];
}

- (IBAction)refeshGmapClick:(id)sender 
{
    [self loadLocations:0];
}

- (IBAction)chooseDistanceClick:(id)sender
{
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    
    
    [actionSheet addButtonWithTitle:@"250 Metern"];
    [actionSheet addButtonWithTitle:@"300 Metern"];
    [actionSheet addButtonWithTitle:@"350 Metern"];
    [actionSheet addButtonWithTitle:@"400 Metern"];
    [actionSheet addButtonWithTitle:@"450 Metern"];
    [actionSheet addButtonWithTitle:@"4500 Metern"];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    [actionSheet release];
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"GMAP -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"GMAP -> viewDidLoad");
    [super viewDidLoad];
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // navigation title
    self.title = @"GMap";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // init data
    locationArray = [[NSMutableArray alloc] init]; 
}

- (void)viewDidUnload
{
    //NSLog(@"GMAP -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"GMAP -> viewWillAppear");
    //NSLog(@"GMAP -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:1 withViewController:self];
    
    // load locations
    [self loadLocations:0];
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark MKAnnotation delegate

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    
    MAnnotation *annotation1 = annotation;
    
    MKAnnotationView *annView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"] autorelease];
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(0, 0);
    
    if (![annotation1.username isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]]) {
        // Set up the Left callout
        UIButton *myDetailButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
        [myDetailButton.titleLabel setText:[NSString stringWithFormat:@"%@", annotation1.username]];
        [myDetailButton setBackgroundImage:[UIImage imageNamed:@"disclosure_bg.png"] forState:UIControlStateNormal];
        [myDetailButton setBackgroundImage:[UIImage imageNamed:@"disclosure_bg.png"] forState:UIControlStateHighlighted];
        myDetailButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        myDetailButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [myDetailButton addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        annView.rightCalloutAccessoryView = myDetailButton;
        [myDetailButton release];
    }

    //NSLog(@"%d", annotation1.isMarked);
    
    NSString *st = @"";
    if (annotation1.isRoot)
        st = @"gmap_blue_point.png";
    else
        st = @"gmap_green_point.png";
    
    UIImage *pinImage = [UIImage imageNamed:st];
    annView.image = pinImage;
    return annView;
}

#pragma mark - 
#pragma mark - ActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)menu didDismissWithButtonIndex:(NSInteger)buttonIndex 
{
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            [self loadLocations:250];
            break;
        case 2:
            [self loadLocations:300];
            break;
        case 3:
            [self loadLocations:350];
            break;
        case 4:
            [self loadLocations:400];
            break;
        case 5:
            [self loadLocations:450];
            break;
        case 6:
            [self loadLocations:4500];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
    
    [locationArray removeAllObjects];
    [locationArray addObjectsFromArray:[responseString JSONValue]];
    [responseString release];
    
    [self addOnGoogleMap];
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
